#Need to install "rgdal" package to successfully run the file.
library(rgdal)
library(leaflet)
library(tidyverse)
library(leaflet.extras)
#Data import
shooting_initial =
read_csv("./data/NYPD_Shooting.csv") %>% janitor::clean_names()
shooting_2021 = read_csv("./data/NYPD_shooting_New.csv") %>% janitor::clean_names()
#A variable name in shooting_new is different from the initial data, change column name in order to merge the data frames
shooting_2021 = shooting_2021 %>%
rename(lon_lat = new_georeferenced_column)
shooting = rbind(shooting_initial, shooting_2021) %>%
mutate(boro = as.factor(boro)) %>%
mutate(location_desc = replace_na(location_desc, "NONE")) %>%
mutate(location_desc = as.factor(location_desc)) %>%
separate(occur_date, into = c("month", "day", "year")) %>%
mutate(month = as.numeric(month)) %>%
arrange(year, month) %>%
# mutate(month = month.name[month]) %>%
mutate(year = as.character(year)) %>%
mutate(boro = tolower(boro)) %>%
mutate(boro = if_else(boro == "staten island", "staten_island", boro)) %>%
rename(borough = boro) %>%
mutate(date = str_c(month, day, year, sep = "/")) %>%
select(incident_key, date, everything())
nyc_boro = readOGR("./data/Borough_Boundaries/geo_export_2204bc6b-9c17-46ed-8a67-7245a1e15877.shp", layer = "geo_export_2204bc6b-9c17-46ed-8a67-7245a1e15877", verbose = FALSE)
shooting_map = shooting %>%
mutate_at(c("perp_age_group", "perp_sex", "perp_race"), funs(ifelse(is.na(.), "UNKNOWN", .))) %>%
mutate(labels = str_c("<b>Incident Key: </b>", incident_key,
"<br>", "<b>Date: </b>", date,
"<br>", "<b>Borough: </b>", borough,
"<br>", "<b>Murdered: </b>", statistical_murder_flag,
"<br>", "<b>Perpetrator's Race: </b>", perp_race,
"<br>", "<b>Victim's Race: </b>", vic_race,
"<br>", "<b>Perpetrator's Age: </b>", perp_age_group,
"<br>", "<b>Victim's Age: </b>", vic_age_group
))
Shooting Incidents Across Space
polygon_color <- colorFactor(
palette = "viridis",
domain = as.factor(nyc_boro@data$boro_name))
shooting_map %>%
leaflet() %>%
addTiles() %>%
addProviderTiles("CartoDB.Positron") %>%
addMarkers(lng = ~longitude, lat = ~latitude, popup = ~labels,
clusterOptions = markerClusterOptions()) %>%
addPolygons(data = nyc_boro,
weight = 0.85,
fillColor = ~polygon_color(nyc_boro@data$boro_name),
# fillOpacity = 0.6,
color = "#BDBDC3",
label = ~nyc_boro@data$boro_name)